# Create your views here.
from rest_framework.views import APIView
from rest_framework.response import Response
from users.models import UserModel,SfLogin
from django.http import HttpResponse
import re,string,requests
import random,time,json
from random import randint

from celery_tasks.sms_code.tasks import send_message
from datetime import datetime
from utils.my_redis import r
from django.contrib.auth.hashers import check_password,make_password

# 注册
from django.conf import settings
# settings.configure(DEBUG=True) # 声明


from captcha.image import ImageCaptcha
class Imgcode(APIView):
    def get(self,request,uuid):
        code= ''.join(random.sample(string.ascii_letters + string.digits, 4))
        cap = ImageCaptcha()
        img_code = cap.generate(code)
        r.set_str(uuid,code,120)
        return HttpResponse(img_code,content_type='image/png')




class SendSmsCode(APIView):
    def get(self,request):
        mobile = request.GET.get('mobile')
        img_code = request.GET.get('img_code')
        uuid = request.GET.get('uuid')
        if not all([mobile,img_code,uuid]):
            return Response({'code': 401, 'msg': '信息不完整'})
        r_code = r.get_str(uuid)
        if not r_code:
            return Response({'code': 401, 'msg': '图片验证码过期'})

        print(r_code)
        if img_code.lower() != r_code.decode().lower():
            return Response({'code': 401, 'msg': '图片验证码错误'})
        data = randint(100000, 999999)
        resp = send_message(mobile,data)
        print('resp>>>',resp,type(resp)) # resp:json字典
        if resp:
            # 短信发送成功后，写入redis便于后边校验
            r.set_str('sms_%s'%mobile,data,600)
            return Response({'msg':'发送成功','code':200,'data':data})
        else:
            return Response({'msg':'发送失败','code':500})


class Register(APIView):
    def post(self,request):
        password = request.data.get('password')
        mobile = request.data.get('mobile')
        user_type = int(request.data.get('user_type'))
        code = request.data.get('code')
        new_code = r.get_str('sms_%s' % mobile)
        if not all([password,mobile,code]):
            return Response({'code': 204, 'msg': '信息不完整'})
        if not re.findall(r'^1[3-9]\d{9}$', mobile):
            return Response({'code': 204, 'msg': '手机号格式错误'})
        if UserModel.objects.filter(mobile=mobile):
            return Response({'code': 400, 'msg': '手机号重复'})
        if new_code.decode()!=code:
            return Response({"code": 400, "msg": "验证码错误"})
        s = datetime.strftime(datetime.now(), "%m%d")
        n = s + mobile[-4:]
        username='用户_'+n
        new_pwd = make_password(password)
        UserModel.objects.create(username=username,password=new_pwd,mobile=mobile,user_type=user_type)
        return Response({'code': 200, 'msg': '注册完成'})

# 登录



import jwt
from django.conf import settings

def login_jwt_token(user):
    payload={
        'userid': user.id,
        'username': user.username,
        'mobile': user.mobile,
        "exp_time": int(time.time())
    }

    token=jwt.encode(payload=payload,key=settings.SECRET_KEY,algorithm='HS256')
    return token




class Login(APIView):
    def post(self,request):
        mobile = request.data.get('mobile')
        pwd= request.data.get('password')

        if not mobile:
            return Response({'code': 404, 'msg': '手机号为空'})
        if not re.findall(r'^\w{6,20}$', pwd):
            return Response({'code': 204, 'msg': '密码格式错误'})
        try:
            user= UserModel.objects.get(mobile=mobile)
        except Exception as e:
            print(e)
            return Response({'code': 404, 'msg': '用户不存在'})
        print(user.password)
        if not check_password(pwd, user.password):
            return Response({'code': 204, 'msg': '账号或密码错误'})
        token= login_jwt_token(user)
        return Response({
            'code': 200,
            'msg': '欢迎用户%s登录'% user.username,
            'token': token
        })

# 第三方登录

class Sina(APIView):
    def get(self):
        # App Key   应用ID
        client_id = "3674019597"
        # App Secret
        client_secret = "7ae99bc0d54ead29fc8d1b9fabd78587"
        # 微博回调网址
        redirect_uri = "http://127.0.0.1:8000/users/weiboCallback/"
        # 微博跳转网址
        sina_url = "https://api.weibo.com/oauth2/authorize"

        auth_url = sina_url + f"?client_id={client_id}&redirect_uri={redirect_uri}"

        # 返回跳转地址
        return Response({'code': 200, 'msg': 'ok','url':auth_url})

from django.shortcuts import redirect
from utils.my_jwt import myjwt
class Sf_Loginview(APIView):
    def get(self):
        code = self.get_query_argument("code")
        data = {"client_id": '3674019597', "client_secret": "7ae99bc0d54ead29fc8d1b9fabd78587",
                "grant_type": "authorization_code",
                'redirect_uri': 'http://127.0.0.1:8000/users/weiboCallback/', 'code': code}
        res1 = requests.post('https://api.weibo.com/oauth2/access_token', data=data)
        mes = json.loads(res1.text)
        uid = mes['uid']
        token = mes['access_token']
        res=SfLogin.objects.get(uid=uid)
        if res:
            jwt = {"data": {"userid": res["id"], "mobile": res["mobile"], "exptime": int(time.time())}}
            token = myjwt.jwt_encode(jwt)

            redirect("http://localhost:8080/updatoken?token=" + token + "&userid=" + str(res['id']))
        else:
            redirect("http://localhost:8000/login")
    def post(self):
        data = json.loads(self.request.body)
        mobile = data['phone']
        uid = data['uid']
        token = data['token']
        add_spl = "insert into user(mobile) values(%s) " % (mobile)
        dbs.add(add_spl)
        sql = "select * from user where mobile=%s"%mobile
        res = dbs.findone(sql)
        if res:
            ad_sql = "insert into sf_login(userid, webfrom, token, uid) values(%d,'weibo','%s','%s')"%(res['id'], token, uid)
            dbs.add(ad_sql)
            dbs.commit()
        jwt = {"data": {"userid": res["id"], "mobile": res["mobile"],"exptime": int(time.time())}}
        token = myjwt.jwt_encode(jwt)
        return Response({'code': 200, 'msg': 'ok', 'token': token})






class Anlis(APIView):
    def get(self,request):
        a=settings.SECRET_KEY
        print(a)
        return Response({
            'msg':a
        })